package org.ww.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.ww.commonutils.R;
import org.ww.commonutils.commentvo.MemberComment;
import org.ww.edu.bean.Comment;
import org.ww.edu.client.MemberClient;
import org.ww.edu.mapper.CommentMapper;
import org.ww.edu.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.ww.servicebase.exceptionhandler.GuliException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author ww
 * @since 2020-11-10
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private MemberClient memberClient;

    @Override
    public Map<String, Object> pageComment(Long page, Long limit,String courseId) {
        //创建分页对象，设置相应的条件
        Page<Comment> commentPage=new Page<>(page,limit);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.orderByDesc("gmt_create");
        //进行分页查询
        baseMapper.selectPage(commentPage,wrapper);
        //将分页对象中的值取出
        List<Comment> records = commentPage.getRecords();
        long current = commentPage.getCurrent();
        long pages = commentPage.getPages();
        long size = commentPage.getSize();
        long total = commentPage.getTotal();
        boolean hasNext = commentPage.hasNext();
        boolean hasPrevious = commentPage.hasPrevious();
        //封装成map
        Map<String, Object> map = new HashMap<>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    /**
     * 添加评论
     * @param comment
     * @param memberId
     */
    @Override
    public void addComment(String memberId,Comment comment) {

        //1 获取用户信息
        MemberComment member = memberClient.getUserInfoById(memberId);

        if(member==null){
            throw new GuliException(20001,"请先进行登录!!!");
        }
        //2 添加评论
        comment.setMemberId(member.getId());
        comment.setAvatar(member.getAvatar());
        comment.setNickname(member.getNickname());

        baseMapper.insert(comment);
    }
}
